package com.frxuexi.apps

import android.annotation.SuppressLint
import android.os.Environment
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.apps.entity.AppsData
import com.frxuexi.apps.entity.AppsEntity
import com.frxuexi.apps.intent.AppsIntent
import com.frxuexi.apps.viewmodel.AppsViewModel
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.BaseTitle
import com.frxuexi.lib_base.RequestType
import com.frxuexi.lib_base.UiState
import com.frxuexi.lib_base.download.DownloadState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun AppsPage(
    navHostController: NavHostController,
    scope: CoroutineScope = rememberCoroutineScope(),
    vm: AppsViewModel = hiltViewModel()
) {
    var list = remember {
        SnapshotStateList<AppsData>()
    }

    val apkPath by lazy {
        BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
    }

    //是否显示进度框
    var isShow by remember {
        mutableStateOf(false)
    }

    LaunchedEffect(key1 = "", block = {
        scope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess -> {
                        if (it.type == RequestType.DEFAULT) {
                            list.addAll(it.data as Collection<AppsData>)
                            Log.i("===", list.size.toString())
                        } else if (it.type == RequestType.DOWNLOAD) {
                            isShow = false//关闭进度框
                            ToastUtils.showLong("下载成功")
                            Log.i("===", "下载成功")

                        }
                    }

                    is UiState.onError -> {
                        Log.i("===", it.msg)
                    }

                    else -> {}
                }
            }
        }

        scope.launch {
            vm.sendIntent(AppsIntent.getClientApps(mapOf(Pair("userId", 1), Pair("page", 1))))
        }
    })


    Column {
        BaseTitle(navHostController = navHostController, title = "在线应用")
        Box(contentAlignment = Alignment.Center) {
            if (isShow) {
                CircularProgressIndicator(
                    modifier = Modifier.width(50.dp),
                    color = MaterialTheme.colorScheme.secondary,
                    trackColor = MaterialTheme.colorScheme.surfaceVariant,
                )
            }
            Column {
                list.forEach {
                    AppsList(it = it) {
                        isShow = true//进度框显示
                        vm.sendIntent(
                            AppsIntent.downloadApk(
                                it.apkUrl,
                                apkPath + "/" + it.appName + ".apk"
                            )
                        )
                    }
                }
            }

        }


    }

}

@Composable
fun AppsList(it: AppsData, onClick: (AppsEntity) -> Unit) {
    Text(text = it.title)
    LazyVerticalGrid(
        verticalArrangement = Arrangement.spacedBy(5.dp),
        columns = GridCells.Fixed(3),
        content = {
            items(it.appsList) {
                AppsItem(entity = it) {
                    onClick(it)
                }
            }
        })
}


@Composable
fun AppsItem(entity: AppsEntity, onClick: (AppsEntity) -> Unit) {
    var isShow by remember {
        mutableStateOf(false)
    }
    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.clickable {
        isShow = true
    }) {
        AsyncImage(model = entity.appIcon, contentDescription = "", modifier = Modifier.size(40.dp))
        Text(text = entity.appName)
    }

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false }, confirmButton = {
            TextButton(onClick = {
                onClick(entity)
                isShow = false
            }) {
                Text(text = "确定")
            }
        }, dismissButton = {
            TextButton(onClick = { isShow = false }) {
                Text(text = "取消")
            }
        },
            title = { Text(text = "下载") }, text = { Text(text = "确认下载吗？") })
    }

}